import AxNotification from '@/components/AxBase/AxNotification';
import request from '@/utils/request';
// import fetch from '@/utils/request';
// import { fetch } from 'umi-request';

export const axhttp = {
  async get(url, params) {
    // return request(url, {
    //   method: 'get',
    //   params,
    // });
    return new Promise((resolve, reject) => {
      request(url, {
        method: 'get',
        params,
      })
        .then(res => {
          if (res) {
            if (res.success === true) {
              return resolve({
                ...res,
              });
            }
            if (res.message) {
              AxNotification.error({
                message: `请求错误：${res.message}`,
              });
              return resolve(`请求错误：${res.message}`);
            }
            if (res.statusText && res.statusText !== 'Unauthorized') {
              return resolve(`请求错误：${res.statusText}`);
            }
          } else {
            AxNotification.error({
              message: '请求暂无响应',
            });
            return resolve('请求暂无响应');
          }
        })
        .catch(err => {
          AxNotification.error({
            message: err,
          });
          return resolve(err);
        });
    });
  },
  async post(url, formData) {
    const data = new FormData();
    Object.keys(formData).map(item => {
      data.append(item, formData[item]);
    });

    return new Promise((resolve, reject) => {
      request(url, {
        method: 'post',
        data: data,
      })
        .then(res => {
          if (res) {
            if (res.success === true) {
              return resolve(res);
            }
            if (res.message) {
              AxNotification.error({
                message: `请求错误：${res.message}`,
              });
              return resolve(`请求错误：${res.message}`);
            }
            if (res.statusText && res.statusText !== 'Unauthorized') {
              return resolve(`请求错误：${res.statusText}`);
            }
          } else {
            AxNotification.error({
              message: '请求暂无响应',
            });
            return resolve('请求暂无响应');
          }
        })
        .catch(err => {
          AxNotification.error({
            message: err,
          });
          return resolve(err);
        });
    });
  },
  async getFile(url, params) {
    const res = request(url, {
      method: 'get',
      params,
      responseType: 'blob',
    });
    return res;
  },
  async fetchFormList(url, data) {
    const ax_token = localStorage.getItem('ax-auth-token');
    if (typeof ax_token === 'string') {
      const body = new URLSearchParams();
      for (const property in data) {
        if (property == 'sort' || property == 'filter') {
          body.set(property, JSON.stringify(data[property]));
        } else {
          body.set(property, data[property]);
        }
      }

      return (
        fetch(url, {
          method: 'post',
          mode: 'cors',
          headers: {
            Authorization: ax_token,
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          },
          body,
        })
          .then(res => res.json())
          .catch(error => { })
          // .catch(error => console.error('Error:', error))
          .then(json => {
            if (json && json.success === true) {
              return {
                list: json.data.rows,
                pagination: {
                  current: json.data.currentPage,
                  pageSize: json.data.pageSize,
                  total: json.data.total,
                },
              };
            }
          })
      );
    }

    return null;
  },
  async fetchForm(url, data) {
    const ax_token = localStorage.getItem('ax-auth-token');
    if (typeof ax_token === 'string') {
      const body = new URLSearchParams();
      for (const property in data) {
        if (property == 'sort' || property == 'filter') {
          body.set(property, JSON.stringify(data[property]));
        } else {
          body.set(property, data[property]);
        }
      }
      return (
        fetch(url, {
          method: 'post',
          mode: 'cors',
          headers: {
            Authorization: ax_token,
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          },
          body,
        })
          .then(res => res.json())
          .catch(error => { })
          // .catch(error => console.error('Error:', error))
          .then(json => {
            if (json && json.success === true) {
              return json.data.data;
            }
          })
      );
    }

    return null;
  },
  async fetchJson(url, json) {
    const ax_token = localStorage.getItem('ax-auth-token');
    if (typeof ax_token === 'string') {
      return fetch(url, {
        method: 'post',
        mode: 'cors',
        headers: {
          Authorization: ax_token,
          'X-Requested-With': 'XMLHttpRequest',
          'Content-Type': 'application/json;charset=UTF-8',
        },
        body: JSON.stringify(json),
      }).then(res => {
        if (res && res.success === true) {
          return res.data;
        }
      });
    }

    return null;
  },
  /** get方法处理列表数据 */
  async getFormList(url, params, data) {
    params = {
      ...params,
      ...data,
    };
    return new Promise((resolve, reject) => {
      request(url, {
        method: 'get',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        },
        params,
      })
        .then(res => {
          if (res) {
            const {
              data = {
                rows: [],
                currentPage: 1,
                pageSize: 20,
                total: 0,
              },
            } = res;
            if (res.success === true) {
              return resolve({
                success: true,
                list: data.rows,
                footer: data.footer,
                pagination: {
                  current: data.currentPage,
                  pageSize: data.pageSize,
                  total: data.total,
                },
              });
            }
            if (res.message) {
              AxNotification.error({
                message: `请求错误：${res.message}`,
              });
              return resolve(`请求错误：${res.message}`);
            }
            if (res.statusText && res.statusText !== 'Unauthorized') {
              return resolve(`请求错误：${res.statusText}`);
            }
          } else {
            AxNotification.error({
              message: '请求暂无响应',
            });
            return resolve('请求暂无响应');
          }
        })
        .catch(err => {
          AxNotification.error({
            message: err,
          });
          return resolve(err);
        });
    });
  },
  /** get方法处理Tree数据 */
  async getFormTree(url, params, data) {
    params = {
      ...params,
      ...data,
    };
    return new Promise((resolve, reject) => {
      request(url, {
        method: 'get',
        requestType: 'form',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        },
        params,
      })
        .then(res => {
          if (res) {
            if (res.success === true) {
              return resolve({
                success: true,
                list: res.data,
              });
            }
            if (res.message) {
              AxNotification.error({
                message: `请求错误：${res.message}`,
              });
              return resolve(`请求错误：${res.message}`);
            }
            if (res.statusText && res.statusText !== 'Unauthorized') {
              return resolve(`请求错误：${res.statusText}`);
            }
          } else {
            AxNotification.error({
              message: '请求暂无响应',
            });
            return resolve('请求暂无响应');
          }
        })
        .catch(err => {
          AxNotification.error({
            message: err,
          });
          return resolve(err);
        });
    });
  },
  /** get方法处理列表数据（无分页） */
  async getFormData(url, params, data) {
    params = {
      ...params,
      ...data,
    };
    return new Promise((resolve, reject) => {
      request(url, {
        method: 'get',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        },
        params,
      })
        .then(res => {
          if (res) {
            if (res.success === true) {
              return resolve({
                success: true,
                list: res.data || [],
              });
            }
            if (res.message) {
              AxNotification.error({
                message: `请求错误：${res.message}`,
              });
              return resolve(`请求错误：${res.message}`);
            }
            if (res.statusText && res.statusText !== 'Unauthorized') {
              return resolve(`请求错误：${res.statusText}`);
            }
          } else {
            AxNotification.error({
              message: '请求暂无响应',
            });
            return resolve('请求暂无响应');
          }
        })
        .catch(err => {
          AxNotification.error({
            message: err,
          });
          return resolve(err);
        });
    });
  },
  /** post方法处理列表数据 */
  async postFormList(url, params, data) {
    return new Promise((resolve, reject) => {
      request(url, {
        method: 'post',
        requestType: 'form',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        },
        params,
        data,
      })
        .then(res => {
          if (res) {
            if (res.success === true) {
              return resolve({
                success: true,
                list: res.data.rows,
                pagination: {
                  current: res.data.currentPage,
                  pageSize: res.data.pageSize,
                  total: res.data.total,
                },
              });
            }
            if (res.message) {
              AxNotification.error({
                message: `请求错误：${res.message}`,
              });
              return resolve(`请求错误：${res.message}`);
            }
            if (res.statusText && res.statusText !== 'Unauthorized') {
              return resolve(`请求错误：${res.statusText}`);
            }
          } else {
            AxNotification.error({
              message: '请求暂无响应',
            });
            return resolve('请求暂无响应');
          }
        })
        .catch(err => {
          AxNotification.error({
            message: err,
          });
          return resolve(err);
        });
    });
  },
  async postForm(url, params, data) {
    return new Promise((resolve, reject) => {
      request(url, {
        method: 'post',
        requestType: 'form',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        },
        params,
        data,
      })
        .then(res => {
          if (res) {
            if (res.success === true) {
              return resolve(res);
            }
            if (res.message) {
              AxNotification.error({
                message: `请求错误：${res.message}`,
              });
              return resolve(`请求错误：${res.message}`);
            }
            if (res.statusText && res.statusText !== 'Unauthorized') {
              return resolve(`请求错误：${res.statusText}`);
            }
          } else {
            AxNotification.error({
              message: '请求暂无响应',
            });
            return resolve('请求暂无响应');
          }
        })
        .catch(err => {
          AxNotification.error({
            message: err,
          });
          return resolve(err);
        });
    });
  },
  async postJson(url, params, json) {
    return new Promise((resolve, reject) => {
      request(url, {
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
        },
        params,
        data: json,
      })
        .then(res => {
          if (res) {
            if (res.success === true) {
              return resolve(res);
            }
            if (res.message) {
              AxNotification.error({
                message: `请求错误：${res.message}`,
              });
              return resolve(`请求错误：${res.message}`);
            }
            if (res.statusText && res.statusText !== 'Unauthorized') {
              return resolve(`请求错误：${res.statusText}`);
            }
          } else {
            AxNotification.error({
              message: '请求暂无响应',
            });
            return resolve('请求暂无响应');
          }
        })
        .catch(err => {
          AxNotification.error({
            message: err,
          });
          return resolve(err);
        });
    });
  },
  async getX(url, params, method = 'get') {
    return request(url, {
      method,
      params,
    })
      .then(res => {
        if (res) {
          if (res.success === true) {
            return Promise.resolve({
              ...res,
            });
          }
          if (res.message) {
            return Promise.reject(`请求错误：${res.message}`);
          }
          if (res.statusText && res.statusText !== 'Unauthorized') {
            return Promise.reject(`请求错误：${res.statusText}`);
          }
          return Promise.resolve({
            success: true,
          });
        } else {
          return Promise.reject('请求暂无响应');
        }
      })
      .catch(err => {
        AxNotification.error({
          message: err,
        });
        return Promise.reject(err);
      });
  },
  /** get方法处理列表数据 */
  async getListX(url, params, data, method = 'get') {
    params = {
      ...params,
      ...data,
    };

    return request(url, {
      method,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
      params,
    }).then(res => {
      if (res) {
        const {
          data = {
            rows: [],
            currentPage: 1,
            pageSize: 20,
            total: 0,
          },
        } = res;
        if (res.success === true) {
          return Promise.resolve({
            success: true,
            list: data.rows,
            footer: data.footer,
            pagination: {
              current: data.currentPage,
              pageSize: data.pageSize,
              total: data.total,
            },
          });
        }
        if (res.message) {
          return Promise.reject(`请求错误：${res.message}`);
        }
        if (res.statusText && res.statusText !== 'Unauthorized') {
          return Promise.reject(`请求错误：${res.statusText}`);
        }
        return Promise.resolve({
          success: true,
          list: data.rows,
          footer: data.footer,
          pagination: {
            current: data.currentPage,
            pageSize: data.pageSize,
            total: data.total,
          },
        });
      } else {
        return Promise.reject('请求暂无响应');
      }
    }).catch(err => {
      AxNotification.error({
        message: err,
      });
      return Promise.reject(err);
    });
  },
  /** get方法处理Tree数据 */
  async getTreeX(url, params, data) {
    params = {
      ...params,
      ...data,
    };
    return request(url, {
      method: 'get',
      requestType: 'form',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
      params,
    })
      .then(res => {
        if (res) {
          if (res.success === true) {
            return Promise.resolve({
              success: true,
              list: res.data,
            });
          }
          if (res.message) {
            return Promise.reject(`请求错误：${res.message}`);
          }
          if (res.statusText && res.statusText !== 'Unauthorized') {
            return Promise.reject(`请求错误：${res.statusText}`);
          }
          return Promise.resolve({
            success: true,
            list: [],
          });
        } else {
          return Promise.reject('请求暂无响应');
        }
      })
      .catch(err => {
        AxNotification.error({
          message: err,
        });
        return Promise.reject(err);
      });
  },
  /** get方法处理列表数据（无分页） */
  async getDataX(url, params, data, method = 'get') {
    params = {
      ...params,
      ...data,
    };
    return request(url, {
      method,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
      params,
    })
      .then(res => {
        if (res) {
          if (res.success === true) {
            return Promise.resolve({
              success: true,
              list: res.data || [],
            });
          }
          if (res.message) {
            return Promise.reject(`请求错误：${res.message}`);
          }
          if (res.statusText && res.statusText !== 'Unauthorized') {
            return Promise.reject(`请求错误：${res.statusText}`);
          }
          return Promise.resolve({
            success: true,
            list: [],
          });
        } else {
          return Promise.reject('请求暂无响应');
        }
      })
      .catch(err => {
        AxNotification.error({
          message: err,
        });
        return Promise.reject(err);
      });
  },
  async postFormX(url, params, data) {
    return request(url, {
      method: 'post',
      requestType: 'form',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
      params,
      data,
    })
      .then(res => {
        if (res) {
          if (res.success === true) {
            return Promise.resolve(res);
          }
          if (res.message) {
            return Promise.reject(`请求错误：${res.message}`);
          }
          if (res.statusText && res.statusText !== 'Unauthorized') {
            return Promise.reject(`请求错误：${res.statusText}`);
          }
        } else {
          return Promise.reject('请求暂无响应');
        }
      })
      .catch(err => {
        AxNotification.error({
          message: err,
        });
        return Promise.reject(err);
      });
  },
};

export function handleResponse(response) {
  if (response && response.success) return Promise.resolve(response);
  else return Promise.reject(response);
}

/** 构造effects方法
 * @param type axhttp中的请求方法,如'getFormList',无需引用axhttp
 * @param url 请求地址 如url.read
 * @param putType put调用的方法，如 'save', 非必填
 * */
export function makeEffects(type, url, putType) {
  return function* handle({ params, payload }, { call, put }) {
    const response = yield call(axhttp[type], url, params, payload);
    if (response && response.success) {
      if (putType) { yield put({ type: putType, payload: response, }) }
      return Promise.resolve(response);
    }
    else return Promise.reject(response);
  }
}
/** 构造Model方法
 * @param effects effects方法名
 * @param ajaxType axhttp中的请求方法,默认'postForm',无需引用axhttp
 * @param reducerName 数据处理方法名
 * @param stateName 数据state名
 * @param stateType 数据类型，默认'list'， 标准带分页，可选'obj'
 * @param urlType url库调用名，默认与effects相同
 * */
export function createModel(config) {
  let model = { effects: {}, reducers: {}, state: {} }
  let { url, namespace, list } = config
  model.namespace = namespace
  if (list && list.length > 0) {
    list.forEach(i => {
      let { effects, ajaxType = 'postForm', reducerName = false, stateName, stateType = 'list', urlType = effects } = i;
      //构造effects
      model.effects[effects] = makeEffects(ajaxType, url[urlType], reducerName);
      //构造reducers
      if (reducerName) {
        model.reducers[reducerName] = (state, action) => {
          let obj = { ...state };
          obj[stateName] = action.payload
          return obj;
        }
        //构造state
        if (stateType == 'list') model.state[stateName] = { list: [], pagination: {} }
        else if (stateType == 'obj') model.state[stateName] = {}
      }
    })
    return model
  }
}
